package vn.edu.saigontech.ncms.web.ajaxtags;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.hibernate.Transaction;

import net.sourceforge.ajaxtags.servlets.BaseAjaxServlet;
import net.sourceforge.ajaxtags.xml.AjaxXmlBuilder;
import vn.edu.saigontech.ncms.model.program.Level;
import vn.edu.saigontech.ncms.model.program.Program;
import vn.edu.saigontech.ncms.service.ProgramService;
import vn.edu.saigontech.ncms.util.Checker;
import vn.edu.saigontech.ncms.util.HibernateUtil;

@SuppressWarnings("serial")
public class ProgramLevelSearchServlet extends BaseAjaxServlet {
	@Override
	public String getXmlContent(HttpServletRequest request, HttpServletResponse response) {
		String programId = request.getParameter("programId");
		AjaxXmlBuilder xml = new AjaxXmlBuilder(); 
		Session session = null;
		Transaction trans = null;
		List<Level> levels = new ArrayList<Level>();
		try {
			session = HibernateUtil.getCurrentSession();
			trans = session.beginTransaction();
			Long id = Long.parseLong(programId);
			Program program = ProgramService.INSTANCE.findById(id);
			if(Checker.isNotNull(program)) {
				levels = new ArrayList<Level>(program.getLevels());
			}
			trans.commit();
		}
		catch (NumberFormatException e) {
			// NOTHING TODO IS TODO S.THING
		} catch(Exception ex) {
			if(trans != null) {
				trans.rollback();
			}
			ex.printStackTrace();
		}
		finally {
			if(session != null) {
				session.close();
			}
		}
		xml.addItem("", true, "");
		for(Level level : levels) {
			xml.addItem(level.getName(), true, level.getId().toString());
		}
		return xml.toString();
	}
}
